Does allocating cooperative individuals to high-degree nodes prevent isolation?

round = NULL
gameID = NULL 
nodes = NULL
meanDegree = NULL
meanDegreeCoop = NULL #mean degree among those who cooperated
meanDegreeDefect = NULL #mean degree among those who defected
meanDist = NULL #mean shortest path length divided by the maximum possible path length (Nvertices - 1)
maxDist = NULL #max shortest path length divided by the maximum possible path length (Nvertices - 1)
coefGlobal = NULL #global clustering coefficient
percentCoop = NULL #proportion of those who cooperated
percentCoopPopular = NULL #proportion of those who cooperated, among those with degree >=10
coopEnv = NULL 
assort = NULL

for(i in 1:length(g.isolation)){
    round[i] =  mean(V(g.isolation[[i]])$round)
    gameID[i] = V(g.isolation[[i]])$gameID[1]
    nodes[i] = vcount(g.isolation[[i]])
    meanDegree[i] = mean(igraph::degree(g.isolation[[i]]),na.rm=TRUE)
    meanDegreeCoop[i] = mean(igraph::degree(g.isolation[[i]])[V(g.isolation[[i]])$behavior=="C"],na.rm=TRUE)
    meanDegreeDefect[i] = mean(igraph::degree(g.isolation[[i]])[V(g.isolation[[i]])$behavior=="D"],na.rm=TRUE)
    meanDist[i] = mean(distances(g.isolation[[i]])[distances(g.isolation[[i]])!=0 & distances(g.isolation[[i]])!=Inf],na.rm=TRUE) / length(V(g.isolation[[i]])-1)
    maxDist[i] = max(distances(g.isolation[[i]])[distances(g.isolation[[i]])!=0 & distances(g.isolation[[i]])!=Inf],na.rm=TRUE) / length(V(g.isolation[[i]])-1)
    coefGlobal[i] = transitivity(g.isolation[[i]], type="global")
    percentCoop[i] = prop.table(table(V(g.isolation[[i]])$behavior))["C"]
    percentCoopPopular[i] = prop.table(table(V(g.isolation[[i]])$behavior[igraph::degree(g.isolation[[i]])>=6]))["C"]
    coopEnv[i] = sum(ifelse(V(g.isolation[[i]])$behavior=="C",1,0)*igraph::degree(g.isolation[[i]])/sum(igraph::degree(g.isolation[[i]])),na.rm=TRUE)
    assort[i] = assortativity(g.isolation[[i]], V(g.isolation[[i]])$behavior == "C")
}

smallWorld = data.frame(
  round = round,
  gameID = gameID,
  nodes = nodes,
  meanDegree = meanDegree,
  meanDegreeCoop = meanDegreeCoop,
  meanDegreeDefect = meanDegreeDefect,
  diffDegreeCD = meanDegreeCoop - meanDegreeDefect,
  meanDist = meanDist,
  maxDist = maxDist,
  coefGlobal = coefGlobal,
  percentCoop = percentCoop,
  percentCoopPopular = percentCoopPopular,
  coopEnv = coopEnv,
  assort = assort
)


round = NULL
gameID = NULL
visibleWealth = NULL
n=1
for(i in unique(cdata$round)){
  for(m in unique(cdata$gameID)){
    round[n] = as.numeric(i)-1
    gameID[n] = m
    visibleWealth[n] = ifelse(cdata[cdata$round==i & cdata$gameID==m,]$showScore[1]=="true",1,0)
    n=n+1
  }
}

smallWorld.2 = data.frame(
  round = round,
  gameID = gameID,
  visibleWealth = visibleWealth
)

smallWorld = merge(smallWorld, smallWorld.2, by=c("gameID","round"), all.x=TRUE)

smallWorld.initial = subset(smallWorld, smallWorld$round==0)

#percent of people that end up being isolated for each gameID
percentIsolated = NULL
percentIsolated = aggregate(isolated ~ gameID, data=sample.wide, FUN=max, na.rm=TRUE)
smallWorld.initial = merge(smallWorld.initial[c("gameID","meanDegree","meanDegreeCoop","meanDegreeDefect","diffDegreeCD","meanDist","coefGlobal","visibleWealth","percentCoop","percentCoopPopular","coopEnv","assort")],percentIsolated, by="gameID", all.x=TRUE)

percentIsolated = NULL
percentIsolated = aggregate(isolated ~ gameID, data=sample.wide, FUN=mean, na.rm=TRUE)
percentIsolated = percentIsolated %>% rename(
  percentIsolated = isolated
)
smallWorld.initial = merge(smallWorld.initial,percentIsolated, by="gameID", all.x=TRUE)




reg = glm(isolated ~ coopEnv, 
      data = smallWorld.initial,
      family = binomial(link = "logit"))
summary(reg)
## 
## Call:
## glm(formula = isolated ~ coopEnv, family = binomial(link = "logit"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -0.6489  -0.4914  -0.4395  -0.3854   2.3384  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)
## (Intercept)  -0.8002     1.6395  -0.488    0.626
## coopEnv      -2.1872     2.5728  -0.850    0.395
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 52.013  on 79  degrees of freedom
## Residual deviance: 51.282  on 78  degrees of freedom
## AIC: 55.282
## 
## Number of Fisher Scoring iterations: 5
reg = glm(isolated ~ coopEnv*percentCoop, 
      data = smallWorld.initial,
      family = binomial(link = "logit"))
summary(reg)
## 
## Call:
## glm(formula = isolated ~ coopEnv * percentCoop, family = binomial(link = "logit"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -0.7581  -0.5129  -0.3847  -0.2979   2.5705  
## 
## Coefficients:
##                     Estimate Std. Error z value Pr(>|z|)
## (Intercept)           -6.739      8.192  -0.823    0.411
## coopEnv               -8.483     16.193  -0.524    0.600
## percentCoop           20.749     16.034   1.294    0.196
## coopEnv:percentCoop   -9.081     19.775  -0.459    0.646
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 52.013  on 79  degrees of freedom
## Residual deviance: 48.836  on 76  degrees of freedom
## AIC: 56.836
## 
## Number of Fisher Scoring iterations: 5
reg = glm(isolated ~ assort, 
      data = smallWorld.initial,
      family = binomial(link = "logit"))
summary(reg)
## 
## Call:
## glm(formula = isolated ~ assort, family = binomial(link = "logit"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -0.8087  -0.4639  -0.3327  -0.2150   2.6431  
## 
## Coefficients:
##             Estimate Std. Error z value Pr(>|z|)    
## (Intercept)  -3.3112     0.7398  -4.476 7.62e-06 ***
## assort      -10.6817     4.6011  -2.322   0.0203 *  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 40.020  on 64  degrees of freedom
## Residual deviance: 33.269  on 63  degrees of freedom
##   (15 observations deleted due to missingness)
## AIC: 37.269
## 
## Number of Fisher Scoring iterations: 6
reg = glm(isolated ~ assort*percentCoop, 
      data = smallWorld.initial,
      family = binomial(link = "logit"))
summary(reg)
## 
## Call:
## glm(formula = isolated ~ assort * percentCoop, family = binomial(link = "logit"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -0.7953  -0.4511  -0.3392  -0.2241   2.6261  
## 
## Coefficients:
##                    Estimate Std. Error z value Pr(>|z|)
## (Intercept)         -3.4008     3.7606  -0.904    0.366
## assort             -14.8971    21.6781  -0.687    0.492
## percentCoop          0.2359     5.5394   0.043    0.966
## assort:percentCoop   7.1996    34.4835   0.209    0.835
## 
## (Dispersion parameter for binomial family taken to be 1)
## 
##     Null deviance: 40.020  on 64  degrees of freedom
## Residual deviance: 33.194  on 61  degrees of freedom
##   (15 observations deleted due to missingness)
## AIC: 41.194
## 
## Number of Fisher Scoring iterations: 6
reg = glm(percentIsolated ~ coopEnv, 
      data = smallWorld.initial, 
      family = gaussian(link = "identity"))
summary(reg)
## 
## Call:
## glm(formula = percentIsolated ~ coopEnv, family = gaussian(link = "identity"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##       Min         1Q     Median         3Q        Max  
## -0.013339  -0.008598  -0.006745  -0.004587   0.117036  
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)  0.01846    0.01166   1.583    0.118
## coopEnv     -0.01722    0.01732  -0.994    0.323
## 
## (Dispersion parameter for gaussian family taken to be 0.0005112187)
## 
##     Null deviance: 0.040380  on 79  degrees of freedom
## Residual deviance: 0.039875  on 78  degrees of freedom
## AIC: -375.29
## 
## Number of Fisher Scoring iterations: 2
reg = glm(percentIsolated ~ coopEnv*percentCoop, 
      data = smallWorld.initial, 
      family = gaussian(link = "identity"))
summary(reg)
## 
## Call:
## glm(formula = percentIsolated ~ coopEnv * percentCoop, family = gaussian(link = "identity"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##       Min         1Q     Median         3Q        Max  
## -0.014683  -0.009669  -0.006671  -0.003141   0.115792  
## 
## Coefficients:
##                     Estimate Std. Error t value Pr(>|t|)
## (Intercept)         -0.01736    0.05317  -0.326    0.745
## coopEnv             -0.03845    0.10335  -0.372    0.711
## percentCoop          0.11389    0.10197   1.117    0.268
## coopEnv:percentCoop -0.06003    0.12200  -0.492    0.624
## 
## (Dispersion parameter for gaussian family taken to be 0.0005144455)
## 
##     Null deviance: 0.040380  on 79  degrees of freedom
## Residual deviance: 0.039098  on 76  degrees of freedom
## AIC: -372.87
## 
## Number of Fisher Scoring iterations: 2
reg = glm(percentIsolated ~ assort, 
      data = smallWorld.initial, 
      family = gaussian(link = "identity"))
summary(reg)
## 
## Call:
## glm(formula = percentIsolated ~ assort, family = gaussian(link = "identity"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##       Min         1Q     Median         3Q        Max  
## -0.017732  -0.010336  -0.006163  -0.000788   0.119912  
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)  
## (Intercept)  0.003475   0.003089   1.125   0.2649  
## assort      -0.064495   0.026242  -2.458   0.0167 *
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.0004921539)
## 
##     Null deviance: 0.033978  on 64  degrees of freedom
## Residual deviance: 0.031006  on 63  degrees of freedom
##   (15 observations deleted due to missingness)
## AIC: -306.66
## 
## Number of Fisher Scoring iterations: 2
reg = glm(percentIsolated ~ assort*percentCoop, 
      data = smallWorld.initial, 
      family = gaussian(link = "identity"))
summary(reg)
## 
## Call:
## glm(formula = percentIsolated ~ assort * percentCoop, family = gaussian(link = "identity"), 
##     data = smallWorld.initial)
## 
## Deviance Residuals: 
##       Min         1Q     Median         3Q        Max  
## -0.017938  -0.009107  -0.005072  -0.002206   0.119805  
## 
## Coefficients:
##                     Estimate Std. Error t value Pr(>|t|)  
## (Intercept)         0.001917   0.016882   0.114   0.9100  
## assort             -0.232569   0.120569  -1.929   0.0584 .
## percentCoop         0.002524   0.024046   0.105   0.9167  
## assort:percentCoop  0.257715   0.178889   1.441   0.1548  
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.0004884538)
## 
##     Null deviance: 0.033978  on 64  degrees of freedom
## Residual deviance: 0.029796  on 61  degrees of freedom
##   (15 observations deleted due to missingness)
## AIC: -305.24
## 
## Number of Fisher Scoring iterations: 2
# #MSM
# # estimation of denominator of ip weights
# #cooperatorの数以外は全てRandom(Erdos-Renyi random graphにより決まるため)なので、coopEnvはpercentCoopで調整すれば十分か
# den.fit.obj <- lm(coopEnv ~ percentCoop + I(percentCoop^2), data = smallWorld.initial)
# p.den <- predict(den.fit.obj, type = "response")
# dens.den <- dnorm(smallWorld.initial$coopEnv, p.den, summary(den.fit.obj)$sigma)
# 
# # estimation of numerator of ip weights
# num.fit.obj <- lm(coopEnv ~ 1, data = smallWorld.initial)
# p.num <- predict(num.fit.obj, type = "response")
# dens.num <- dnorm(smallWorld.initial$coopEnv, p.num, summary(num.fit.obj)$sigma)
# 
# smallWorld.initial$sw.a = dens.num/dens.den
# summary(smallWorld.initial$sw.a)
# 
# msm.sw.cont <-geepack::geeglm(isolated ~ coopEnv, 
#                  data=smallWorld.initial, weights=sw.a, family = binomial(link="logit"), id=gameID, corstr="independence")
# summary(msm.sw.cont)
# 
# msm.sw.cont <-geepack::geeglm(percentIsolated ~ coopEnv, 
#                  data=smallWorld.initial, weights=sw.a, family = gaussian(link="identity"), id=gameID, corstr="independence")
# summary(msm.sw.cont)


ggplot(data = smallWorld.initial, aes(x = coopEnv, y = percentIsolated)) + 
  geom_point() +
  ggtitle("Percent isolated") +
  scale_x_continuous("Cooporative environment") +  
  scale_y_continuous("Percent of individuals isolated") + 
  scale_fill_continuous(type = "viridis")

ggplot(data = smallWorld.initial, aes(x = assort, y = percentIsolated)) + 
  geom_point() +
  ggtitle("Percent isolated") +
  scale_x_continuous("Assortativity coefficient of initial C/D") +  
  scale_y_continuous("Percent of individuals isolated") + 
  scale_fill_continuous(type = "viridis")
## Warning: Removed 15 rows containing missing values (`geom_point()`).

Simulation 1

All graphs start as Erdos-Renyi random newtorks

Cooperators have low degrees

#Define degrees of isolation
isolationDegree = 0

#number of iterations per arm
iterations = 100

modelForPrediction = "random forest" #"linear" or "random forest"

# List of manipulating parameters of experiments
#L : number of rounds
#V : Visible or not
#A : Income of a rich-group subject
#B : Income of a poor-group subject
#R : Probability to be assigned to a rich group
#I : Number of the same-parameter trial

R = 0.5
I = 0
L = 10


trends.df = data.frame()
  

  
  
for(A in c(1150,700,500)){
  for(V in c(0,1)){
      
      V = V
      A = A
      if(A==1150){B = 200} #high inequality
      if(A==700){B = 300} #low inequality
      if(A==500){B = 500} #no inequality
  
      if(modelForPrediction=="random forest"){
        source(paste(rootdir,"R/models.R",sep="/"))
        if(V==0){
          model1<-model1.invisible(redo=FALSE)
          model2<-model2.invisible(redo=FALSE)
          model3<-model3(redo=FALSE)
          }
        if(V==1){
          model1<-model1.visible(redo=FALSE)
          model2<-model2.visible(redo=FALSE)
          model3<-model3(redo=FALSE)
          }
      }
      
      df.netIntLowDegree = data.frame(
        coopFrac = NULL,
        avgCoop = NULL, 
        avgCoopFinal = NULL, 
        percentIsolation = NULL,
        isolation = NULL,
        percentIsolationC = NULL,
        percentIsolationD = NULL,
        nCommunities = NULL,
        communitySize = NULL,
        assortativityInitial = NULL,
        assortativityFinal = NULL,
        conversionRate = NULL,
        conversionToD = NULL, 
        conversionToC = NULL, 
        transitivity = NULL, 
        degree = NULL, 
        degreeC = NULL, 
        degreeD = NULL,
        meanConversionToD = NULL, 
        meanConversionToC = NULL, 
        degreeLost = NULL,
        degreeLostC = NULL,
        degreeLostD = NULL
      )
  
      #Here, factionCoop=0 will be the control: no rearranging of nodes will take place
      for(frac in c(0,0.25,0.5,0.75,1)){
        #nodes in the top fractionCoop degrees will automatically be a cooperator
        fractionCoop = frac
        
          coopFrac = NULL
          avgCoop = NULL
          homophilyC = NULL
          homophilyD = NULL
          heterophily = NULL
          avgCoopFinal = NULL
          percentIsolation = NULL
          isolation = NULL
          percentIsolationC = NULL
          percentIsolationD = NULL
          nCommunities = NULL
          communitySize = NULL
          assortativityInitial = NULL
          assortativityFinal = NULL
          conversionRate = NULL
          conversionToD = NULL 
          conversionToC = NULL
          transitivity = NULL
          degree = NULL
          degreeC = NULL
          degreeD = NULL
          meanConversionToD = NULL 
          meanConversionToC = NULL
          degreeLost = NULL
          degreeLostC = NULL
          degreeLostD = NULL
          avg_wealth = NULL
          gini = NULL
          for(m in c(1:iterations)){
            # Section 1. NOTES, packages, and Parameters
            #Importing library
            library(igraph) # for network graphing
            library(reldist) # for gini calculatio
            library(boot) # for inv.logit calculation
            #Two prefixed functions
            #rank
            rank1 = function(x) {rank(x,na.last=NA,ties.method="average")[1]} #a smaller value has a smaller rank.
            #gini mean difference (a.k.a. mean difference: please refer to https://stat.ethz.ch/pipermail/r-help/2003-April/032782.html)
            gmd = function(x) {
             x1 = na.omit(x)
             n = length(x1)
            tmp = 0
             for (i in 1:n) {
             for (j in 1:n) {
             tmp <- tmp + abs(x1[i]-x1[j])
             }
             }
            answer = tmp/(n*n)
             return(answer)
            }
        
            
            
            
            # List of fixed parameters of experiments (assumptions)
            #Rewiring rate = 0.3
            #GINI coefficient (can be known by A or B)
            GINI = 0*as.numeric(A==500) + 0.2*as.numeric(A %in% c(700,850)) + 0.4*as.numeric(A ==1150)
            #Collecting data frame (final output data frame)
            result = data.frame(round=0:L,n_par=NA,n_A=NA,avg_coop=NA,avg_degree=NA,avg_wealth=NA,gini=NA,gmd=NA,avg_coop_A=NA,avg_degree_A=NA,avg_wealth_A=NA,gini_A=NA,gmd_A=NA,avg_coop_B=NA,avg_degree_B=NA,avg_wealth_B=NA,gini_B=NA,gmd_B=NA,isolation=NA,percentIsolation=NA,meanConversionToD=NA,meanConversionToC=NA,degreeLost=NA,degreeLostC=NA,degreeLostD=NA)
            #_A is for a richer group and _B is for a poorer group
            
            
            #####################################################
            # Section 1.5: Practice rounds 1 to 2, to determine C/D in round 1
            
            N = 17 # median of the number of participants over rounds.
            node_rp0 = data.frame(ego_id=1:N, round=0)
            node_import = node_rp0
            
            for (k in 1:2){
              node_rX = node_import #Importing data
              node_rX$round = node_rX$round + 1
              node_rX[is.na(node_rX$prev_degree)==1,"prev_degree"] = 0
              node_rX[is.na(node_rX$prev_local_rate_coop)==1,"prev_local_rate_coop"] = 0
              #Only this calculation needs to change from Round 1
              if (k==1) {
                node_rX$prob_coop = inv.logit(1.099471) 
              } else {
                node_rX$prob_coop = inv.logit((-0.02339288) + (1.46068980)*as.numeric(node_rX$prev_coop==1))
              } 
              
              node_rX$coop = apply(data.frame(node_rX$prob_coop),1,function(x) {sample(1:0,1,prob=c(x,(1-x)))})
              
              node_rX$prev_coop = node_rX$coop
                
              assign(paste("coop_rp",k, sep=""),node_rX$coop)
              
              #For the loop
              node_import = node_rX
            }
            
            #cooperation rate in the practice rounds
            coop_rp = apply(cbind(coop_rp1,coop_rp2),1,mean)
      
            #####################################################
            # Section 2: Round 0 (Agents and environments)
            #Node data generation
            N = 17 # median of the number of participants over rounds.
            node_r0 = data.frame(ego_id=1:N, round=0)
            node_r0$coop_rp = ifelse(coop_rp==1,"C","D")
            node_r0$group = sample(c("rich","poor"),N,replace=TRUE,prob=c(R,1-R)) #R is defined as the probability to be assigned to the rich group
            node_r0$initial_wealth = ifelse(node_r0$group=="rich",A,B)
            #Link data generation
            ego_list = NULL
            for (i in 1:N) { ego_list = c(ego_list,rep(i,N)) }
            link_r0 = data.frame(ego_id=ego_list,alt_id=rep(1:N,N))
            link_r0 = link_r0[(link_r0$ego_id < link_r0$alt_id),] #The link was bidirectional, and thus the half and self are omitted.
            link_r0$connected = sample(0:1,dim(link_r0)[1],replace=TRUE,prob=c(0.7,0.3)) #Initial rewiring rate is fixed, 0.3
            link_r0c_ego = link_r0[link_r0$connected==1,]
            link_r0c_alt = link_r0[link_r0$connected==1,]
            colnames(link_r0c_alt) = c("alt_id","ego_id","connected")
            link_r0c = rbind(link_r0c_ego,link_r0c_alt) #this is bidirectional (double counted) for connected ties.
            link_r0c = link_r0c[order(link_r0c$ego_id),]
            link_r0c$alternumber = NA #putting the number for each alter in the same ego
            link_r0c[1,]$alternumber = 1
            for (i in 1:(dim(link_r0c)[1]-1))
              {if (link_r0c[i,]$ego_id == link_r0c[i+1,]$ego_id)
                {link_r0c[i+1,]$alternumber = link_r0c[i,]$alternumber + 1}
              else
                {link_r0c[i+1,]$alternumber = 1}
              #print(i)
              }
            link_r0c2 = reshape(link_r0c, direction = "wide", idvar=c("ego_id","connected"), timevar="alternumber")
            link_r0c2$initial_degree = apply(link_r0c2[,colnames(link_r0c2)[substr(colnames(link_r0c2),1,6) == "alt_id"]],1,function(x){length(na.omit(x))}) #Degree of each ego
            link_r0c2[is.na(link_r0c2$initial_degree)==1,"initial_degree"] = 0
            #Reflect the degree and initial local gini coefficient into the node data
            node_r0 = merge(x=node_r0,y=link_r0c2,all.x=TRUE,all.y=FALSE,by="ego_id")
            node_r0$initial_avg_env_wealth = NA
            node_r0$initial_local_gini = NA #local gini coefficient of the ego and connecting alters
            node_r0$initial_rel_rank = NA #local rank of ego among the ego and connecting alters (divided by the number of the go and connecting alters)
            for (i in 1:(dim(node_r0)[1])){
              node_r0[i,]$initial_avg_env_wealth = mean(na.omit(node_r0[node_r0$ego_id %in%
              node_r0[i,colnames(node_r0)[substr(colnames(node_r0),1,6) %in% c("ego_id","alt_id")]],"initial_wealth"]))
              node_r0[i,]$initial_local_gini = gini(na.omit(node_r0[node_r0$ego_id %in% node_r0[i,colnames(node_r0)[substr(colnames(node_r0),1,6)
              %in% c("ego_id","alt_id")]],"initial_wealth"]))
              node_r0[i,]$initial_rel_rank = rank1(na.omit(node_r0[node_r0$ego_id %in% node_r0[i,colnames(node_r0)[substr(colnames(node_r0),1,6)
              %in% c("ego_id","alt_id")]],"initial_wealth"]))/length(na.omit(node_r0[node_r0$ego_id %in%
              node_r0[i,colnames(node_r0)[substr(colnames(node_r0),1,6) %in% c("ego_id","alt_id")]],"initial_wealth"]))
              }
            #Finalization of round 0 and Visualization
            #plot(graph.data.frame(link_r0[link_r0$connected==1,],directed=F)) #plot.igraph
            node_r0$everIsolated = 0
            node_r0$maxDegreeLost = NA
            result[result$round==0,2:25] = c(length(node_r0$ego_id),length(node_r0[node_r0$group=="rich",]$ego_id),NA,mean(node_r0$initial_degree),mean(node_r0$initial_wealth),gini(node_r0$initial_wealth),gmd(node_r0$initial_wealth),NA,mean(node_r0[node_r0$group=="rich",]$initial_degree),mean(node_r0[node_r0$group=="rich",]$initial_wealth),gini(node_r0[node_r0$group=="rich",]$initial_wealth),gmd(node_r0[node_r0$group=="rich",]$initial_wealth),NA,mean(node_r0[node_r0$group=="poor",]$initial_degree),mean(node_r0[node_r0$group=="poor",]$initial_wealth),gini(node_r0[node_r0$group=="poor",]$initial_wealth),gmd(node_r0[node_r0$group=="poor",]$initial_wealth),
                                             as.numeric(ifelse(is.na(table(node_r0$initial_degree<=isolationDegree)["TRUE"]),0,1)),
                                             as.numeric(sum(node_r0$everIsolated)/length(node_r0$ego_id)),
                                             NA,
                                             NA,
                                             NA,NA,NA
                                             )
            
            #For the loop at the next round (for round 1, the initial one is the same as the previous [1 prior] one)
            node_import = node_r0
            node_import$initial_coop = NA
            node_import$prev_coop = NA
            node_import$prev_wealth = node_import$initial_wealth
            node_import$prev_degree = node_import$initial_degree
            node_import$prev_avg_env_wealth = node_import$initial_avg_env_wealth
            node_import$prev_local_gini = node_import$initial_local_gini
            node_import$prev_rel_rank = node_import$initial_rel_rank
            node_import$prev_local_rate_coop = NA
            link_import = link_r0
            
            
            #####################################################
            # Section 3: Rounds 1 to 10 or more (behaviors in simulation: the equation of cooperation is different at round 1 because of no history)
            #3-1: Cooperation phase
            for (k in 1:L)
            {
              node_rX = node_import #Importing data
              node_rX$round = node_rX$round + 1
              node_rX[is.na(node_rX$prev_degree)==1,"prev_degree"] = 0
              node_rX[is.na(node_rX$prev_local_rate_coop)==1,"prev_local_rate_coop"] = 0
              #Only this calculation needs to change from Round 1
              if(modelForPrediction=="linear"){
                if (k==1) {
                  node_rX$prob_coop = as.numeric(V==0)*inv.logit((-1.816665) + (2.086067)*coop_rp1 + (1.800153)*coop_rp2) + as.numeric(V==1)*inv.logit((-2.031577) + (2.427157)*coop_rp1 + (1.684193)*coop_rp2 + (-1.528851)*GINI)
                  } else {
                  node_rX$prob_coop = as.numeric(V==0 & node_rX$prev_coop==0)*inv.logit(-1.039916) + as.numeric(V==0 & node_rX$prev_coop==1)*inv.logit(2.062023) + as.numeric(V==1 & node_rX$prev_coop==0)*inv.logit((-0.2574838)*as.numeric(node_rX$prev_avg_env_wealth - node_rX$prev_wealth > 0) + (-1.214198)*GINI + (2.508148)*GINI*as.numeric(node_rX$prev_avg_env_wealth - node_rX$prev_wealth > 0) + (-0.9749075)) + as.numeric(V==1 & node_rX$prev_coop==1)*inv.logit((- 0.6197254)*as.numeric(node_rX$prev_avg_env_wealth - node_rX$prev_wealth > 0) + (-0.7480261)*GINI + (1.169674)*GINI*as.numeric(node_rX$prev_avg_env_wealth - node_rX$prev_wealth > 0) + (1.356784))
                  } 
              }
              if(modelForPrediction=="random forest"){
                if (k==1) {
                    if(V==1){node_rX$prob_coop = predict(model1,
                                                         newdata=
                                                           data.frame(
                                                             behavior.p1 = coop_rp1,
                                                             behavior.p2 = coop_rp2,
                                                             gini = GINI
                                                           ),
                                                         type = "prob"
                                                         )[[1]]$C}
                    else if(V==0){node_rX$prob_coop = predict(model1,
                                                         newdata=
                                                           data.frame(
                                                             behavior.p1 = coop_rp1,
                                                             behavior.p2 = coop_rp2
                                                           ),
                                                         type = "prob"
                                                         )[[1]]$C}
                  } else {
                    if(V==1){node_rX$prob_coop = predict(model2,
                                                         newdata=
                                                           data.frame(
                                                             prevCoop = node_rX$prev_coop,
                                                             gini = GINI,
                                                             alterPrevWealth = node_rX$prev_avg_env_wealth,
                                                             egoPrevWealth = node_rX$prev_wealth
                                                           ),
                                                         type = "prob"
                                                         )[[1]]$C}
                    else if(V==0){node_rX$prob_coop = predict(model2,
                                                         newdata=
                                                           data.frame(
                                                             prevCoop = node_rX$prev_coop,
                                                             alterPrevWealth = node_rX$prev_avg_env_wealth,
                                                             egoPrevWealth = node_rX$prev_wealth
                                                           ),
                                                         type = "prob"
                                                         )[[1]]$C}
                  }
              }
              #####rearrange node degrees before round 1 depending on cooperation in practice rounds!
              if(k==1){
                if(fractionCoop==0){
                  node_rX$prob_coop
                  node_rX$coop = apply(data.frame(node_rX$prob_coop),1,function(x) {sample(1:0,1,prob=c(x,(1-x)))})
                  coop_rp_init = coop_rp
                  }
                if(fractionCoop>0){
                  prob_coop_df = NULL
                  nodesCoop = NULL
                  #nodesCoop = node_rX$prev_degree<=quantile(node_rX$prev_degree,fractionCoop) #assign low-degree nodes to cooperators
                  #assign defectors to designated nodes
                  nodesCoop = node_rX$prev_degree<=floor(quantile(node_rX$prev_degree,fractionCoop)) & node_rX$prev_degree>=floor(quantile(node_rX$prev_degree,fractionCoop-0.25)) 
                  prob_coop_df = 
                    data.frame(
                      prob_coop = rev(node_rX$prob_coop[order(coop_rp)]),
                      node_number = c(which(!nodesCoop),which(nodesCoop))
                    )
                  node_rX$prob_coop = prob_coop_df[order(prob_coop_df$node_number),]$prob_coop
                  #coop_rp of the rearranged nodes
                  coop_rp_init = rev(coop_rp[order(coop_rp)])[order(prob_coop_df$node_number)]
                  node_rX$coop = apply(data.frame(node_rX$prob_coop),1,function(x) {sample(1:0,1,prob=c(x,(1-x)))})
                }
              } else {
                node_rX$coop = apply(data.frame(node_rX$prob_coop),1,function(x) {sample(1:0,1,prob=c(x,(1-x)))})
              }
              if (k==1) {
                node_rX$initial_coop = node_rX$coop
                } else {
                node_rX$initial_coop = node_rX$initial_coop
                }
              node_rX$cost = (-50)*node_rX$coop*node_rX$prev_degree
              node_rX$n_coop_received = NA
              for (i in 1:(dim(node_rX)[1]))
                {
                node_rX[i,]$n_coop_received = sum(node_rX[node_rX$ego_id %in% node_rX[i,colnames(node_rX)[substr(colnames(node_rX),1,6) ==
                "alt_id"]],"coop"])
                }
              node_rX$benefit = 100*node_rX$n_coop_received
              node_rX$payoff = node_rX$cost + node_rX$benefit
              node_rX$wealth = node_rX$prev_wealth + node_rX$payoff
              node_rX$rel_rank = NA
              node_rX$local_rate_coop = NA
              for (i in 1:dim(node_rX)[1])
                {
                node_rX[i,]$rel_rank = rank1(na.omit(node_rX[node_rX$ego_id %in% node_rX[i,colnames(node_rX)[substr(colnames(node_rX),1,6) %in%
                c("ego_id","alt_id")]],"wealth"]))/length(na.omit(node_rX[node_rX$ego_id %in%
                node_rX[i,colnames(node_rX)[substr(colnames(node_rX),1,6) %in% c("ego_id","alt_id")]],"wealth"]))
                node_rX[i,]$local_rate_coop = mean(na.omit(node_rX[node_rX$ego_id %in% node_rX[i,colnames(node_rX)[substr(colnames(node_rX),1,6) %in%
                c("ego_id","alt_id")]],"coop"]))
                }
              node_rX$growth = as.numeric((node_rX$wealth/node_rX$prev_wealth) > 1)
              node_rX = node_rX[,c("ego_id","round","group","prev_degree","initial_wealth","initial_local_gini","initial_coop","coop","wealth","rel_rank","local_rate_coop","growth","everIsolated","maxDegreeLost")] #Pruning the previous-round data (degree is not updating yet)
              
              #3-2: Rewiring phase
              # 30% of ties (unidirectional) are being rewired
              link_rX_1 = link_import #Importing data (bidirectioanl ego-alter [ego_id < alter_id])
              colnames(link_rX_1) = c("ego_id","alt_id","prev_connected")
              link_rX_1$challenge = sample(0:1,dim(link_rX_1)[1],replace=TRUE,prob=c(0.7,0.3)) # The bidirectional ties being rewired are selected (rewiring rate = 0.3).
              ego_node_data =
              node_rX[,c("ego_id","wealth","coop","prev_degree","initial_wealth","initial_local_gini","initial_coop","rel_rank","local_rate_coop","growth")]
              colnames(ego_node_data) =
              c("ego_id","ego_wealth","ego_coop","ego_prev_degree","ego_initial_wealth","ego_initial_local_gini","ego_initial_coop","ego_rel_rank","ego_local_rate_coop","ego_growth")
              alt_node_data =
              node_rX[,c("ego_id","wealth","coop","prev_degree","initial_wealth","initial_local_gini","initial_coop","rel_rank","local_rate_coop","growth")]
              colnames(alt_node_data) =
              c("alt_id","alt_wealth","alt_coop","alt_prev_degree","alt_initial_wealth","alt_initial_local_gini","alt_initial_coop","alt_rel_rank","alt_local_rate_coop","alt_growth")
              link_rX_2 = merge(x=link_rX_1,y=ego_node_data,all.x=TRUE,all.y=FALSE,by="ego_id")
              link_rX_3 = merge(x=link_rX_2,y=alt_node_data,all.x=TRUE,all.y=FALSE,by="alt_id")
              link_rX_3$choice = sample(c("ego","alt"),dim(link_rX_3)[1],replace=TRUE,prob=c(0.5,0.5)) #decision maker for breaking a link, which is a unilateral decision
              #ego_prob: probability of choosing to connect when challenged (asked)
              
              if(modelForPrediction=="linear"){
                link_rX_3$ego_prob = inv.logit((0.5134401)*link_rX_3$prev_connected + (-0.852406)*link_rX_3$ego_coop + (2.96549)*link_rX_3$alt_coop + (-0.1808545))
                link_rX_3$alt_prob = inv.logit((0.5134401)*link_rX_3$prev_connected + (-0.852406)*link_rX_3$alt_coop + (2.96549)*link_rX_3$ego_coop + (-0.1808545))}
              if(modelForPrediction=="random forest"){
                link_rX_3$ego_prob = predict(model3,
                                             newdata=
                                               data.frame(
                                                 previouslyconnected = link_rX_3$prev_connected,
                                                 ego_behavior = link_rX_3$ego_coop,
                                                 alter_behavior = link_rX_3$alt_coop
                                                 ),
                                            type = "prob"
                                             )[[1]]$C
                link_rX_3$alt_prob = predict(model3,
                                             newdata=
                                               data.frame(
                                                 previouslyconnected = link_rX_3$prev_connected,
                                                 ego_behavior = link_rX_3$alt_coop,
                                                 alter_behavior = link_rX_3$ego_coop
                                                 ),
                                            type = "prob"
                                             )[[1]]$C
              }
              link_rX_3$prob_connect = ifelse(link_rX_3$prev_connected == 1, ifelse(link_rX_3$choice == "ego", link_rX_3$ego_prob,
              link_rX_3$alt_prob), link_rX_3$ego_prob*link_rX_3$alt_prob)
              link_rX_3$connect_update = apply(data.frame(link_rX_3$prob_connect),1, function(x) {sample(1:0,1,prob=c(x,(1-x)))})
              link_rX_3$connected = ifelse(link_rX_3$challenge==0,link_rX_3$prev_connected,link_rX_3$connect_update)
              link_rX = link_rX_3[,c("ego_id","alt_id","connected")] #pruning and data is updated
              #Reflect the degree and local gini coefficient into the node data
              link_rXc_ego = link_rX[link_rX$connected==1,]
              link_rXc_alt = link_rX[link_rX$connected==1,]
              colnames(link_rXc_alt) = c("alt_id","ego_id","connected")
              link_rXc = rbind(link_rXc_ego,link_rXc_alt)
              link_rXc = link_rXc[order(link_rXc$ego_id),]
              link_rXc$alternumber = NA
              link_rXc[1,]$alternumber = 1
              for (i in 1:(dim(link_rXc)[1]-1))
                {
                  if (link_rXc[i,]$ego_id == link_rXc[i+1,]$ego_id)
                  {
                  link_rXc[i+1,]$alternumber = link_rXc[i,]$alternumber + 1
                  }
                  else
                  {
                  link_rXc[i+1,]$alternumber = 1
                  }
                  #print(i)
                }
              link_rXc2 = reshape(link_rXc, direction = "wide", idvar=c("ego_id","connected"), timevar="alternumber")
              link_rXc2$degree = apply(link_rXc2[,colnames(link_rXc2)[substr(colnames(link_rXc2),1,3) == "alt"]],1,function(x) {length(na.omit(x))})
              node_rX_final = merge(x=node_rX[,c("ego_id","round","group","initial_wealth","initial_local_gini","initial_coop","coop","wealth","growth","everIsolated","maxDegreeLost")],y=link_rXc2,all.x=TRUE,all.y=FALSE,by="ego_id")
              node_rX_final[is.na(node_rX_final$degree)==1,"degree"] = 0
              node_rX_final$avg_env_wealth = NA
              node_rX_final$local_gini = NA #needs to be updated because the social network changes at the rewiring phase
              node_rX_final$local_rate_coop = NA
              node_rX_final$rel_rank = NA
              for (i in 1:dim(node_rX_final)[1])
                {
                node_rX_final[i,]$avg_env_wealth = mean(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in% c("ego_id","alt_id")]],"wealth"]))
                node_rX_final[i,]$local_gini = gini(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in% c("ego_id","alt_id")]],"wealth"]))
                node_rX_final[i,]$local_rate_coop = mean(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in% c("ego_id","alt_id")]],"coop"]))
                node_rX_final[i,]$rel_rank = rank1(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in%
                c("ego_id","alt_id")]],"wealth"]))/length(na.omit(node_rX_final[node_rX_final$ego_id %in%
                node_rX_final[i,colnames(node_rX_final)[substr(colnames(node_rX_final),1,6) %in% c("ego_id","alt_id")]],"wealth"]))
                node_rX_final[i,]$everIsolated = ifelse(node_rX_final[i,]$everIsolated==1,1,ifelse(node_rX_final[i,]$degree<=isolationDegree,1,0))
                node_rX_final[i,]$maxDegreeLost = pmax(node_r0[i,]$initial_degree - node_rX_final[i,]$degree, node_rX_final[i,]$maxDegreeLost, na.rm=TRUE)
              }
              
              
              #Finalization of round X and Visualization
              #plot(graph.data.frame(link_rX[link_rX$connected==1,],directed=F)) #plot.igraph
              result[result$round==k,2:25] =
              c(length(node_rX_final$ego_id),length(node_rX_final[node_rX_final$group=="rich",]$ego_id),mean(node_rX_final$coop),mean(node_rX_final$degree),mean(node_rX_final$wealth),gini(node_rX_final$wealth),gmd(node_rX_final$wealth),mean(node_rX_final[node_rX_final$group=="rich",]$coop),mean(node_rX_final[node_rX_final$group=="rich",]$degree),mean(node_rX_final[node_rX_final$group=="rich",]$wealth),gini(node_rX_final[node_rX_final$group=="rich",]$wealth),gmd(node_rX_final[node_rX_final$group=="rich",]$wealth),mean(node_rX_final[node_rX_final$group=="poor",]$coop),mean(node_rX_final[node_rX_final$group=="poor",]$degree),mean(node_rX_final[node_rX_final$group=="poor",]$wealth),gini(node_rX_final[node_rX_final$group=="poor",]$wealth),gmd(node_rX_final[node_rX_final$group=="poor",]$wealth),
                                             as.numeric(ifelse(is.na(table(node_rX_final$degree<=isolationDegree)["TRUE"]),0,1)),
                                             as.numeric(sum(node_rX_final$everIsolated)/length(node_rX_final$ego_id)),
                prop.table(table(node_rX_final[node_rX_final$initial_coop==1]$coop))["0"],
                prop.table(table(node_rX_final[node_rX_final$initial_coop==0]$coop))["1"],
                suppressWarnings({mean(node_rX_final$maxDegreeLost,na.rm=TRUE)}),
                suppressWarnings({mean(node_rX_final[node_rX_final$initial_coop==1]$maxDegreeLost,na.rm=TRUE)}),
                suppressWarnings({mean(node_rX_final[node_rX_final$initial_coop==0]$maxDegreeLost,na.rm=TRUE)})
                )
              
              #For the loop
              node_import = node_rX_final
              colnames(node_import)[colnames(node_import) %in%
              c("coop","wealth","growth","degree","avg_env_wealth","local_gini","local_rate_coop","rel_rank")] =
              c("prev_coop","prev_wealth","prev_growth","prev_degree","prev_avg_env_wealth","prev_local_gini","prev_local_rate_coop","prev_rel_rank")
              link_import = link_rX
              #print(paste0("Round ",k," is done."))
            }
            
           
            trends.df = rbind(trends.df,cbind(result[c("round","gini","gmd","avg_wealth","avg_coop","avg_degree")],V,GINI,fractionCoop))
            
            link_rX_final = data.table::melt(setDT(node_rX_final),
                                     measure = patterns('alt_id'),
                                     variable.name = 'linkNumber', 
                                     value.name = c('alt_id'))
            link_rX_final = data.frame(link_rX_final)[c("ego_id","alt_id")]
            link_rX_final = link_rX_final[complete.cases(link_rX_final),]
            link_rX_final = data.frame(t(unique(apply(link_rX_final, 1, function(x) sort(x))))) %>% distinct(X1, X2)
            node_g_final = data.frame(node_rX_final)[c("ego_id","initial_coop","coop")]
            node_g_final$initial_coop = factor(node_g_final$initial_coop)
            
            g_rX_final = graph_from_data_frame(link_rX_final, directed = FALSE, vertices=node_g_final)
            g_r0 = graph_from_data_frame(link_r0[link_r0$connected==1,][1:2], directed = FALSE, vertices=node_r0)
            
            E(g_r0)$coopEdgeC = sapply(E(g_r0), function(e) prod(ifelse(V(g_r0)[inc(e)]$coop_rp=="C",1,0)))
            E(g_r0)$coopEdgeD = sapply(E(g_r0), function(e) prod(ifelse(V(g_r0)[inc(e)]$coop_rp=="D",1,0)))
            E(g_r0)$coopEdgeCD = sapply(E(g_r0), function(e) ifelse(sum(ifelse(V(g_r0)[inc(e)]$coop_rp=="C",1,0))==1,1,0))
            
            #C-assortativity, defined as number of observed C-C edges out of total possible C-C edges
            homophilyC[m] = sum(E(g_r0)$coopEdgeC) / (table(V(g_r0)$coop_rp)["C"]*(table(V(g_r0)$coop_rp)["C"]-1)/2)
            #D-assortativity, defined as number of observed C-C edges out of total possible C-C edges
            homophilyD[m] = sum(E(g_r0)$coopEdgeD) / (table(V(g_r0)$coop_rp)["D"]*(table(V(g_r0)$coop_rp)["D"]-1)/2)
            #heterophily, defined as number of observed C-D edges out of total possible C-D edges
            heterophily[m] = sum(E(g_r0)$coopEdgeCD) / (table(V(g_r0)$coop_rp)["C"]*table(V(g_r0)$coop_rp)["D"])
            
            coopFrac[m] = fractionCoop
            avgCoop[m] = prop.table(table(V(g_r0)$coop_rp))["C"]
            avgCoopFinal[m] = result[result$round==10,]$avg_coop
            percentIsolation[m] = max(result[result$round>=1,]$percentIsolation)
            isolation[m] = max(result[result$round>=1,]$isolation)
            #percentage of isolation among those who cooperated in both practice rounds
            percentIsolationC[m] = sum(node_rX_final[coop_rp_init==1,]$everIsolated)/length(node_rX_final[coop_rp_init==1,]$everIsolated)
            #percentage of isolation among those who defected at least once in practice rounds
            percentIsolationD[m] = sum(node_rX_final[coop_rp_init<=0.5,]$everIsolated)/length(node_rX_final[coop_rp_init<=0.5,]$everIsolated)
            
            nCommunities[m] = max(membership(cluster_louvain(g_rX_final)),na.rm=TRUE)
            communitySize[m] = mean(table(membership(cluster_louvain(g_rX_final))),na.rm=TRUE)
            assortativityInitial[m] = assortativity(g_r0, V(g_r0)$coop_rp == "C")
            assortativityFinal[m] = assortativity(g_rX_final, V(g_r0)$coop_rp == "C")
            conversionRate[m] = prop.table(table(V(g_rX_final)$coop == ifelse(V(g_r0)$coop_rp=="C","1","0")))["FALSE"]
            conversionToD[m] = prop.table(table(V(g_rX_final)$coop[V(g_r0)$coop_rp == "C"]))["0"]
            conversionToC[m] = prop.table(table(V(g_rX_final)$coop[V(g_r0)$coop_rp == "C"]))["1"]
            transitivity[m] = mean(transitivity(g_rX_final, type="global"),na.rm=TRUE)
            degree[m] = mean(igraph::degree(g_rX_final),na.rm=TRUE)
            degreeC[m] = mean(igraph::degree(g_r0)[coop_rp_init==1],na.rm=TRUE)
            degreeD[m] = mean(igraph::degree(g_r0)[coop_rp_init<=0.5],na.rm=TRUE)
            meanConversionToD[m] = mean(result[result$round>=2,]$meanConversionToD, na.rm=TRUE)
            meanConversionToC[m] = mean(result[result$round>=2,]$meanConversionToC, na.rm=TRUE)
            degreeLost[m] = result[result$round==10,]$degreeLost
            degreeLostC[m] = result[result$round==10,]$degreeLostC
            degreeLostD[m] = result[result$round==10,]$degreeLostD
            avg_wealth[m] = result[result$round==10,]$avg_wealth
            gini[m] = result[result$round==10,]$gini
        
          }
          
        df.netIntLowDegree = rbind(df.netIntLowDegree,
                          data.frame(
                            coopFrac = coopFrac,
                            avgCoop = avgCoop,
                            avgCoopFinal = avgCoopFinal,
                            percentIsolation = percentIsolation,
                            isolation = isolation,
                            percentIsolationC = percentIsolationC,
                            percentIsolationD = percentIsolationD,
                            nCommunities = nCommunities,
                            communitySize = communitySize,
                            assortativityInitial = assortativityInitial,
                            assortativityFinal = assortativityFinal,
                            conversionRate = conversionRate,
                            conversionToD = conversionToD, 
                            conversionToC = conversionToC, 
                            homophilyC = homophilyC,
                            homophilyD = homophilyD,
                            heterophily = heterophily,
                            transitivity = transitivity, 
                            degree = degree, 
                            degreeC = degreeC, 
                            degreeD = degreeD,
                            meanConversionToD = meanConversionToD, 
                            meanConversionToC = meanConversionToC,
                            degreeLost = degreeLost,
                            degreeLostC = degreeLostC,
                            degreeLostD = degreeLostD,
                            avg_wealth = avg_wealth,
                            gini = gini
                            ))
        #plot(g_r0,vertex.color=V(g_rX_final)$initial_coop,vertex.label=ifelse(is.na(V(g_rX_final)$initial_coop),"NA",ifelse(V(g_rX_final)$initial_coop==1,"C","D")),main=paste("fracCoop=",frac,", round 0",sep=""))
        #plot(g_rX_final,vertex.color=V(g_rX_final)$initial_coop,vertex.label=ifelse(is.na(V(g_rX_final)$initial_coop),"NA",ifelse(V(g_rX_final)$initial_coop==1,"C","D")),main=paste("fracCoop=",frac,", final round",sep=""))
        
      }
      
    sum.netIntLowDegree <- data.frame(
      df.netIntLowDegree %>% 
        group_by(coopFrac) %>%
          summarise(
            mean.isolation = mean(isolation),
            ci.isolation   = 1.96 * sd(isolation)/sqrt(n()),
            mean.percentIsolation = mean(percentIsolation),
            ci.percentIsolation   = 1.96 * sd(percentIsolation)/sqrt(n()),
            mean.percentIsolationC = mean(percentIsolationC,na.rm=TRUE),
            ci.percentIsolationC   = 1.96 * sd(percentIsolationC,na.rm=TRUE)/sqrt(sum(isolation)),
            mean.percentIsolationD = mean(percentIsolationD,na.rm=TRUE),
            ci.percentIsolationD   = 1.96 * sd(percentIsolationD,na.rm=TRUE)/sqrt(sum(isolation)),
            mean.avgCoop = mean(avgCoop,na.rm=TRUE),
            ci.avgCoop   = 1.96 * sd(avgCoop,na.rm=TRUE)/sqrt(n()),
            mean.avgCoopFinal = mean(avgCoopFinal,na.rm=TRUE),
            ci.avgCoopFinal   = 1.96 * sd(avgCoopFinal,na.rm=TRUE)/sqrt(n()),
            mean.nCommunities = mean(nCommunities,na.rm=TRUE),
            ci.nCommunities   = 1.96 * sd(nCommunities,na.rm=TRUE)/sqrt(n()),
            mean.communitySize = mean(communitySize,na.rm=TRUE),
            ci.communitySize   = 1.96 * sd(communitySize,na.rm=TRUE)/sqrt(n()),
            mean.assortativityInitial = mean(assortativityInitial,na.rm=TRUE),
            ci.assortativityInitial   = 1.96 * sd(assortativityInitial,na.rm=TRUE)/sqrt(n()),
            mean.assortativityFinal = mean(assortativityFinal,na.rm=TRUE),
            ci.assortativityFinal   = 1.96 * sd(assortativityFinal,na.rm=TRUE)/sqrt(n()),
            mean.conversionRate = mean(conversionRate,na.rm=TRUE),
            ci.conversionRate   = 1.96 * sd(conversionRate,na.rm=TRUE)/sqrt(n()),
            mean.conversionToD = mean(conversionToD,na.rm=TRUE),
            ci.conversionToD   = 1.96 * sd(conversionToD,na.rm=TRUE)/sqrt(n()),
            mean.conversionToC = mean(conversionToC,na.rm=TRUE),
            ci.conversionToC   = 1.96 * sd(conversionToC,na.rm=TRUE)/sqrt(n()),
            mean.homophilyC = mean(homophilyC,na.rm=TRUE),
            ci.homophilyC   = 1.96 * sd(homophilyC,na.rm=TRUE)/sqrt(n()),
            mean.homophilyD = mean(homophilyD,na.rm=TRUE),
            ci.homophilyD   = 1.96 * sd(homophilyD,na.rm=TRUE)/sqrt(n()),
            mean.heterophily = mean(heterophily,na.rm=TRUE),
            ci.heterophily   = 1.96 * sd(heterophily,na.rm=TRUE)/sqrt(n()),
            mean.transitivity = mean(transitivity,na.rm=TRUE),
            ci.transitivity   = 1.96 * sd(transitivity,na.rm=TRUE)/sqrt(n()),
            mean.degree = mean(degree,na.rm=TRUE),
            ci.degree   = 1.96 * sd(degree,na.rm=TRUE)/sqrt(n()),
            mean.degreeC = mean(degreeC,na.rm=TRUE),
            ci.degreeC   = 1.96 * sd(degreeC,na.rm=TRUE)/sqrt(n()),
            mean.degreeD = mean(degreeD,na.rm=TRUE),
            ci.degreeD   = 1.96 * sd(degreeD,na.rm=TRUE)/sqrt(n()),
            mean.meanConversionToD = mean(meanConversionToD,na.rm=TRUE),
            ci.meanConversionToD   = 1.96 * sd(meanConversionToD,na.rm=TRUE)/sqrt(n()),
            mean.meanConversionToC = mean(meanConversionToC,na.rm=TRUE),
            ci.meanConversionToC   = 1.96 * sd(meanConversionToC,na.rm=TRUE)/sqrt(n()),
            mean.degreeLost = mean(degreeLost,na.rm=TRUE),
            ci.degreeLost   = 1.96 * sd(degreeLost,na.rm=TRUE)/sqrt(n()),
            mean.degreeLostC = mean(degreeLostC,na.rm=TRUE),
            ci.degreeLostC   = 1.96 * sd(degreeLostC,na.rm=TRUE)/sqrt(n()),
            mean.degreeLostD = mean(degreeLostD,na.rm=TRUE),
            ci.degreeLostD   = 1.96 * sd(degreeLostD,na.rm=TRUE)/sqrt(n()),
            mean.avg_wealth = mean(avg_wealth,na.rm=TRUE),
            ci.avg_wealth   = 1.96 * sd(avg_wealth,na.rm=TRUE)/sqrt(n()),
            mean.gini = mean(gini,na.rm=TRUE),
            ci.gini   = 1.96 * sd(gini,na.rm=TRUE)/sqrt(n())
            )
      )
          
    kable(sum.netIntLowDegree[c(1:9)]) %>% kableExtra::kable_styling(font_size = 10)
    kable(sum.netIntLowDegree[c(1,10:17)]) %>% kableExtra::kable_styling(font_size = 10) 
    kable(sum.netIntLowDegree[c(1,18:25)]) %>% kableExtra::kable_styling(font_size = 10) 
    kable(sum.netIntLowDegree[c(1,26:33)]) %>% kableExtra::kable_styling(font_size = 10) 
    kable(sum.netIntLowDegree[c(1,34:ncol(sum.netIntLowDegree))]) %>% kableExtra::kable_styling(font_size = 10) 
    
    compare_means(percentIsolation ~ coopFrac, data=df.netIntLowDegree)
    compare_means(avgCoop ~ coopFrac, data=df.netIntLowDegree)
    compare_means(avgCoopFinal ~ coopFrac, data=df.netIntLowDegree)
    compare_means(nCommunities ~ coopFrac, data=df.netIntLowDegree)
    compare_means(communitySize ~ coopFrac, data=df.netIntLowDegree)
    compare_means(assortativityInitial ~ coopFrac, data=df.netIntLowDegree)
    compare_means(assortativityFinal ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(conversionRate ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(conversionToD ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(conversionToC ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeC ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeD ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(meanConversionToD ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(meanConversionToC ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeLost ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeLostC ~ coopFrac, data=df.netIntLowDegree)
    #compare_means(degreeLostD ~ coopFrac, data=df.netIntLowDegree)
    
    summary(lm(percentIsolation ~ assortativityInitial, data=df.netIntLowDegree))
    
    #plot(df.netIntLowDegree$assortativityInitial, df.netIntLowDegree$percentIsolation)
    
    
    
    #percentIsolation
    g.percentIsolation = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="percentIsolation", add = "mean_se", color="coopFrac") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.098, method="t.test", color="black") +  
      labs(
        title = paste("Isolation when defectors are assigned to 25% of nodes by degree, ","V=",V,", Gini=",GINI,sep=""),
        x = "Degree percentile of nodes assigned to defectors ",
        y = "Propoption of ever-isolated individuals") +
      annotate("text", x=1, y=0.0990, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0022, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0024, xend = 3.7, yend = -0.0024), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0022, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,0.10)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.percentIsolation)
    
    #percentIsolationC
    #percentage of isolation among those who cooperated in both practice rounds
    g.percentIsolationC = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="percentIsolationC", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.098, method="t.test", color="black") +  
      labs(
        title = paste("Isolation among initial cooperators, ","V=",V,", Gini=",GINI,sep=""),
        x = "Degree percentile of nodes assigned to defectors ",
        y = "Propoption of ever-isolated individuals") +
      annotate("text", x=1, y=0.0990, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0022, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0024, xend = 3.7, yend = -0.0024), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0022, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,0.10)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.percentIsolationC)
    
    #percentIsolationD
    #percentage of isolation among those who defected at least once in practice rounds
    g.percentIsolationD = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="percentIsolationD", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.298, method="t.test", color="black") +  
      labs(
        title = paste("Isolation among initial defectors, ","V=",V,", Gini=",GINI,sep=""),
        x = "Degree percentile of nodes assigned to defectors ",
        y = "Propoption of ever-isolated individuals") +
      annotate("text", x=1, y=0.2990, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0062, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0064, xend = 3.7, yend = -0.0064), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0062, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,0.30)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.percentIsolationD)
      
    #avgCoopFinal
    g.avgCoopFinal = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="avgCoopFinal", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.98, method="t.test", color="black") +  
      labs(
        title = paste("Cooperation in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Degree percentile of nodes assigned to defectors ",
        y = "Propoption of cooperators in final round") +
      annotate("text", x=1, y=0.990, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0212, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0214, xend = 3.7, yend = -0.0214), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0212, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,1.0)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.avgCoopFinal)
    
    #avg_wealth
    g.avg_wealth = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="avg_wealth", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 6800, method="t.test", color="black") +  
      labs(
        title = paste("Wealth in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Degree percentile of nodes assigned to defectors ",
        y = "Average wealth in final round") +
      annotate("text", x=1, y=6900, label= "ref", color="black") +
      annotate("text", x=2.4, y= -162, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -164, xend = 3.7, yend = -164), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -162, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,7000)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.avg_wealth)
    
    #gini
    g.gini = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="gini", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.48, method="t.test", color="black") +  
      labs(
        title = paste("Gini coefficient in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Degree percentile of nodes assigned to defectors ",
        y = "Gini coefficient in final round") +
      annotate("text", x=1, y=0.490, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0112, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0114, xend = 3.7, yend = -0.0114), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0112, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,0.50)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.gini)
    
    #degree
    g.degree = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="degree", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 14.8, method="t.test", color="black") +  
      labs(
        title = paste("Degree in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Degree percentile of nodes assigned to defectors ",
        y = "Mean degree in final round") +
      annotate("text", x=1, y=14.90, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.312, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.314, xend = 3.7, yend = -0.314), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.312, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,15)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.degree)
    
    #transitivity
    g.transitivity = ggbarplot(data=df.netIntLowDegree, x="coopFrac", y="transitivity", add = "mean_se") +
      stat_compare_means(ref.group = "0", label = "p.signif", label.y = 0.98, method="t.test", color="black") +  
      labs(
        title = paste("Transitivity in final round, ","V=",V,", Gini=",GINI,sep=""),
        x = "Degree percentile of nodes assigned to defectors ",
        y = "Transitivity in final round") +
      annotate("text", x=1, y=0.99, label= "ref", color="black") +
      annotate("text", x=2.4, y= -0.0212, label= "Lowest degree nodes assigned to defectors", size=2.5) +
      geom_segment(aes(x = 3.3, y = -0.0214, xend = 3.7, yend = -0.0214), linewidth=0.2, arrow = arrow(length = unit(0.1, "cm"))) +
      annotate("text", x=4.6, y= -0.0212, label= "Highest degree nodes assigned to defectors", size=2.5) +
      theme_bw() +
      theme(plot.title = element_text(hjust = 0.5, size=12),legend.position="none") +
      coord_cartesian(ylim=c(0,1.00)) + 
      scale_x_discrete(labels=c('Control','0-25','25-50','50-75','75-100')) +
      scale_color_manual(values = c('0' = "black",'0.25'="black",'0.5'="black",'0.75'="black",'1'="black")) +
      geom_vline(xintercept = 1.5, linetype = "longdash")
    print(g.transitivity)
    
    #initial C-assortativity     
    plotList <- lapply(
              unique(df.netIntLowDegree$coopFrac),
              function(key) {
                if(key==0){
                  ggplot(data = df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,], aes(x = homophilyC, y = percentIsolation)) + 
                      geom_point() + 
                      scale_x_continuous(paste("C-assortativity, ","Control",sep="")) +
                      scale_y_continuous("Proportion isolated") +
                      geom_smooth(method='lm', formula= y~x) + 
                      stat_cor(method = "pearson")
                }
                else{
                  ggplot(data = df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,], aes(x = homophilyC, y = percentIsolation)) + 
                      geom_point() + 
                      scale_x_continuous(paste("C-assortativity, degree %ile = ",key,sep="")) +
                      scale_y_continuous("Proportion isolated") +
                      geom_smooth(method='lm', formula= y~x) + 
                      stat_cor(method = "pearson")
                }
              }
    )
    plot= ggarrange(plotlist=plotList)
    print(annotate_figure(plot, top = text_grob(paste("Proportion of ever-isolated individuals, ","V=",V,", Gini=", GINI, sep=""), color = "black", face = "bold", size = 10)))
    
    lapply(unique(df.netIntLowDegree$coopFrac),
              function(key) {
                if(key==0){
                  reg = lm(percentIsolation ~ homophilyC + degreeD, data=df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,])
                  print(paste("Regression on proportion of ever-isolated individuals, ","Control"," ; ",sep=""))
                  print(summary(reg)[4]$coefficients)
                }
                else{
                  reg = lm(percentIsolation ~ homophilyC + degreeD, data=df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,])
                  print(paste("Regression on proportion of ever-isolated individuals, degree %ile = ",key," ; ",sep=""))
                  print(summary(reg)[4]$coefficients)
                }
              }
    )
    
    
    
    #initial D-assortativity     
    plotList <- lapply(
              unique(df.netIntLowDegree$coopFrac),
              function(key) {
                if(key==0){
                  ggplot(data = df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,], aes(x = homophilyD, y = percentIsolation)) + 
                      geom_point() +
                      scale_x_continuous(paste("D-assortativity, ","Control",sep="")) + 
                      scale_y_continuous("Proportion isolated") +
                      geom_smooth(method='lm', formula= y~x) + 
                      stat_cor(method = "pearson")
                }
                else{
                  ggplot(data = df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,], aes(x = homophilyD, y = percentIsolation)) + 
                      geom_point() +
                      scale_x_continuous(paste("D-assortativity, degree %ile = ",key,sep="")) + 
                      scale_y_continuous("Proportion isolated") +
                      geom_smooth(method='lm', formula= y~x) + 
                      stat_cor(method = "pearson")
                }
              }
    )
    plot= ggarrange(plotlist=plotList)
    print(annotate_figure(plot, top = text_grob(paste("Proportion of ever-isolated individuals, ","V=",V,", Gini=", GINI, sep=""), color = "black", face = "bold", size = 10)))
    
    lapply(unique(df.netIntLowDegree$coopFrac),
              function(key) {
                if(key==0){
                  reg = lm(percentIsolation ~ homophilyD + degreeD, data=df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,])
                  print(paste("Regression on proportion of ever-isolated individuals, ","Control"," ; ",sep=""))
                  print(summary(reg)[4]$coefficients)
                }
                else{
                  reg = lm(percentIsolation ~ homophilyD + degreeD, data=df.netIntLowDegree[df.netIntLowDegree$coopFrac==key,])
                  print(paste("Regression on proportion of ever-isolated individuals, degree %ile = ",key," ; ",sep=""))
                  print(summary(reg)[4]$coefficients)
                }
              }
    )
    
    }
}
## Loading data last updated on  2023-01-20 20:37:15 
## Call model1.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 20:39:47 
## Call model2.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.
## Warning: package 'reldist' was built under R version 4.1.2
## reldist: Relative Distribution Methods
## Version 1.7-1 created on 2022-05-14.
## copyright (c) 2003, Mark S. Handcock, University of California-Los Angeles
##  For citation information, type citation("reldist").
##  Type help(package="reldist") to get started.
## 
## Attaching package: 'reldist'
## The following object is masked from 'package:arsenal':
## 
##     iqr
## 
## Attaching package: 'boot'
## The following object is masked from 'package:lattice':
## 
##     melanoma
## Warning: The dot-dot notation (`..p.signif..`) was deprecated in ggplot2 3.4.0.
## ℹ Please use `after_stat(p.signif)` instead.
## ℹ The deprecated feature was likely used in the ggpubr package.
##   Please report the issue at <https://github.com/kassambara/ggpubr/issues>.

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0014943986 0.007553466  0.1978428 0.8435821
## homophilyC   0.0145337293 0.013889433  1.0463875 0.2979827
## degreeD     -0.0008330259 0.001290823 -0.6453445 0.5202275
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                Estimate Std. Error   t value     Pr(>|t|)
## (Intercept)  0.03007907 0.01042450  2.885420 0.0048173034
## homophilyC   0.03954713 0.03351792  1.179880 0.2409333076
## degreeD     -0.01061687 0.00278640 -3.810245 0.0002436648
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0074276126 0.006094363  1.2187677 0.2258881
## homophilyC  -0.0278372319 0.017486560 -1.5919216 0.1146561
## degreeD      0.0006088889 0.001396257  0.4360867 0.6637428
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                  Estimate  Std. Error     t value  Pr(>|t|)
## (Intercept)  0.0056390703 0.007382118  0.76388244 0.4467914
## homophilyC  -0.0108662859 0.015733978 -0.69062549 0.4914502
## degreeD     -0.0001038386 0.001435313 -0.07234561 0.9424758
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept) -0.0028613066 0.0043707834 -0.6546439 0.5142464
## homophilyC  -0.0052203138 0.0092608194 -0.5636989 0.5742600
## degreeD      0.0008193364 0.0007217041  1.1352802 0.2590554

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0055329350 0.006569251  0.8422474 0.4017213
## homophilyD  -0.0018858158 0.010189117 -0.1850814 0.8535517
## degreeD     -0.0006622054 0.001644540 -0.4026691 0.6880777
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error    t value     Pr(>|t|)
## (Intercept)  0.036539989 0.008867217  4.1207956 0.0000795603
## homophilyD   0.003333855 0.013077181  0.2549368 0.7993116440
## degreeD     -0.009357685 0.002601166 -3.5974958 0.0005078426
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0037401816 0.005560132  0.6726786 0.5027511
## homophilyD  -0.0114702540 0.008724463 -1.3147232 0.1917029
## degreeD      0.0003120687 0.001361376  0.2292303 0.8191726
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0048897145 0.007031790  0.6953726 0.4884844
## homophilyD  -0.0081844917 0.007256291 -1.1279166 0.2621373
## degreeD     -0.0001489036 0.001367155 -0.1089149 0.9134950
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept) -0.0035746217 0.0041903977 -0.8530507 0.3957327
## homophilyD   0.0018716710 0.0041564789  0.4503021 0.6534975
## degreeD      0.0005898888 0.0007054977  0.8361314 0.4051360
## Loading data last updated on  2023-01-20 21:50:22 
## Call model1.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 21:54:00 
## Call model2.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## Warning: Removed 1 rows containing non-finite values (`stat_summary()`).
## Warning: Removed 1 rows containing non-finite values (`stat_compare_means()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate   Std. Error   t value   Pr(>|t|)
## (Intercept)  0.008148383 0.0041318676  1.972082 0.05144805
## homophilyC  -0.008682440 0.0078274233 -1.109234 0.27007197
## degreeD     -0.001059940 0.0006879791 -1.540657 0.12665640
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.002441184 0.005789419  0.4216631 0.6742040
## homophilyC   0.019817878 0.016805053  1.1792809 0.2411708
## degreeD     -0.001938157 0.001469489 -1.3189330 0.1902968
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyC         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyC         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyC         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0042139062 0.0033196933  1.2693661 0.2073477
## homophilyD  -0.0073585407 0.0050749100 -1.4499845 0.1502886
## degreeD     -0.0003375311 0.0008286853 -0.4073091 0.6846784
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0071884449 0.004915893  1.4622868 0.1468951
## homophilyD  -0.0095629075 0.008224109 -1.1627894 0.2477676
## degreeD     -0.0007186804 0.001434170 -0.5011124 0.6174273
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyD         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyD         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyD         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## Loading data last updated on  2023-01-20 20:37:15 
## Call model1.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 20:39:47 
## Call model2.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## Warning: Removed 1 rows containing non-finite values (`stat_summary()`).
## Warning: Removed 1 rows containing non-finite values (`stat_compare_means()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                  Estimate  Std. Error     t value  Pr(>|t|)
## (Intercept)  0.0062644073 0.009197864  0.68107197 0.4974486
## homophilyC   0.0002350656 0.017424463  0.01349055 0.9892641
## degreeD     -0.0007301189 0.001531496 -0.47673582 0.6346225
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error   t value    Pr(>|t|)
## (Intercept)  0.025411514 0.007829132  3.245764 0.001608291
## homophilyC  -0.028745841 0.022725767 -1.264901 0.208937346
## degreeD     -0.003731244 0.001987215 -1.877624 0.063437016
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0077022390 0.008459510  0.9104828 0.3648249
## homophilyC  -0.0198848274 0.024303504 -0.8181877 0.4152554
## degreeD      0.0001887044 0.002147952  0.0878532 0.9301745
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                 Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.003558012 0.008015821  0.4438737 0.6581225
## homophilyC   0.034629255 0.022542728  1.5361608 0.1277545
## degreeD     -0.002109801 0.001938218 -1.0885260 0.2790601
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error    t value   Pr(>|t|)
## (Intercept)  0.017582833 0.008128287  2.1631659 0.03301151
## homophilyC  -0.033456658 0.015944423 -2.0983298 0.03850161
## degreeD     -0.001002028 0.001254497 -0.7987486 0.42640791
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate  Std. Error   t value  Pr(>|t|)
## (Intercept)  0.008725388 0.007346535  1.187687 0.2378567
## homophilyD   0.015962122 0.011230858  1.421274 0.1584443
## degreeD     -0.002203581 0.001833894 -1.201586 0.2324497
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error   t value    Pr(>|t|)
## (Intercept)  0.017530576 0.006549037  2.676818 0.008727671
## homophilyD   0.023390769 0.010956300  2.134915 0.035287518
## degreeD     -0.006044969 0.001910626 -3.163868 0.002079531
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                 Estimate  Std. Error    t value   Pr(>|t|)
## (Intercept)  0.003867439 0.007923281  0.4881108 0.62657293
## homophilyD   0.016941401 0.009671839  1.7516214 0.08299963
## degreeD     -0.001621855 0.001893780 -0.8564112 0.39388110
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0051234766 0.008100986  0.6324510 0.5285802
## homophilyD  -0.0140833545 0.012403909 -1.1353965 0.2590069
## degreeD      0.0004107086 0.001605865  0.2557554 0.7986812
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error   t value  Pr(>|t|)
## (Intercept)  0.011331183 0.007664504  1.478397 0.1426094
## homophilyD   0.009062353 0.008498141  1.066392 0.2889489
## degreeD     -0.002007249 0.001335897 -1.502547 0.1362727
## Loading data last updated on  2023-01-20 21:50:22 
## Call model1.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 21:54:00 
## Call model2.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## Warning: Removed 1 rows containing non-finite values (`stat_summary()`).
## Warning: Removed 1 rows containing non-finite values (`stat_compare_means()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate   Std. Error   t value   Pr(>|t|)
## (Intercept)  0.008148383 0.0041318676  1.972082 0.05144805
## homophilyC  -0.008682440 0.0078274233 -1.109234 0.27007197
## degreeD     -0.001059940 0.0006879791 -1.540657 0.12665640
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.002441184 0.005789419  0.4216631 0.6742040
## homophilyC   0.019817878 0.016805053  1.1792809 0.2411708
## degreeD     -0.001938157 0.001469489 -1.3189330 0.1902968
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyC         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyC         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyC         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0042139062 0.0033196933  1.2693661 0.2073477
## homophilyD  -0.0073585407 0.0050749100 -1.4499845 0.1502886
## degreeD     -0.0003375311 0.0008286853 -0.4073091 0.6846784
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0071884449 0.004915893  1.4622868 0.1468951
## homophilyD  -0.0095629075 0.008224109 -1.1627894 0.2477676
## degreeD     -0.0007186804 0.001434170 -0.5011124 0.6174273
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyD         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyD         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##             Estimate Std. Error t value Pr(>|t|)
## (Intercept)        0          0     NaN      NaN
## homophilyD         0          0     NaN      NaN
## degreeD            0          0     NaN      NaN
## Loading data last updated on  2023-01-20 20:37:15 
## Call model1.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 20:39:47 
## Call model2.invisible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## Warning: Removed 1 rows containing non-finite values (`stat_summary()`).
## Warning: Removed 1 rows containing non-finite values (`stat_compare_means()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                  Estimate  Std. Error     t value  Pr(>|t|)
## (Intercept)  0.0137623124 0.010710706  1.28491179 0.2018829
## homophilyC  -0.0009954768 0.020290396 -0.04906148 0.9609712
## degreeD     -0.0020095491 0.001783392 -1.12681263 0.2626016
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error   t value    Pr(>|t|)
## (Intercept)  0.023825950 0.007877917  3.024397 0.003188335
## homophilyC  -0.028786707 0.022867375 -1.258855 0.211103966
## degreeD     -0.003273924 0.001999598 -1.637291 0.104810015
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0106020363 0.007726928  1.3720894 0.1732005
## homophilyC  -0.0187299006 0.022198854 -0.8437328 0.4008947
## degreeD     -0.0007153862 0.001961942 -0.3646317 0.7161801
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                  Estimate  Std. Error     t value  Pr(>|t|)
## (Intercept) -0.0004888780 0.008801578 -0.05554436 0.9558190
## homophilyC   0.0206026242 0.024752495  0.83234537 0.4072586
## degreeD     -0.0004239465 0.002128214 -0.19920296 0.8425210
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                  Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0106100023 0.008321449  1.2750186 0.2053798
## homophilyC  -0.0119186403 0.016323328 -0.7301599 0.4670705
## degreeD     -0.0008866005 0.001284309 -0.6903328 0.4916506
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.013270149 0.008643273  1.5353152 0.1279619
## homophilyD  -0.001118580 0.013213219 -0.0846561 0.9327093
## degreeD     -0.001901367 0.002157595 -0.8812437 0.3803643
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error   t value    Pr(>|t|)
## (Intercept)  0.016655753 0.006667432  2.498076 0.014169249
## homophilyD   0.016516978 0.011154371  1.480763 0.141910730
## degreeD     -0.005195607 0.001945167 -2.671034 0.008868779
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                 Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.007232057 0.007269141  0.9948985 0.3222610
## homophilyD   0.013256830 0.008873339  1.4940068 0.1384198
## degreeD     -0.002275930 0.001737431 -1.3099399 0.1933100
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                  Estimate  Std. Error     t value  Pr(>|t|)
## (Intercept)  0.0002162026 0.008871760  0.02436976 0.9806077
## homophilyD  -0.0052440283 0.013584089 -0.38604195 0.7003110
## degreeD      0.0009350208 0.001758656  0.53166786 0.5961716
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                 Estimate  Std. Error    t value  Pr(>|t|)
## (Intercept)  0.008517418 0.007716549  1.1037859 0.2724741
## homophilyD   0.006490967 0.008555847  0.7586586 0.4499350
## degreeD     -0.001419566 0.001344968 -1.0554640 0.2938900
## Loading data last updated on  2023-01-20 21:50:22 
## Call model1.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 21:54:00 
## Call model2.visible(redo=TRUE) to update data.
## Loading data last updated on  2023-01-20 22:02:59 
## Call model3(redo=TRUE) to update data.

## Warning: Removed 1 rows containing non-finite values (`stat_summary()`).
## Warning: Removed 1 rows containing non-finite values (`stat_compare_means()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate   Std. Error    t value    Pr(>|t|)
## (Intercept)  0.016271272 0.0056674770  2.8709903 0.005024393
## homophilyC  -0.008021431 0.0107364866 -0.7471188 0.456799050
## degreeD     -0.002723664 0.0009436666 -2.8862570 0.004805541
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error   t value  Pr(>|t|)
## (Intercept)  0.011345184 0.004689469  2.419290 0.0174146
## homophilyC  -0.014121560 0.013612209 -1.037419 0.3021200
## degreeD     -0.001666738 0.001190296 -1.400272 0.1646224
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0022455566 0.0034801055  0.6452553 0.5202851
## homophilyC   0.0065015212 0.0099980679  0.6502778 0.5170500
## degreeD     -0.0008625701 0.0008836325 -0.9761638 0.3314115
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0050595281 0.0036608969  1.3820461 0.1701320
## homophilyC  -0.0096191806 0.0102954647 -0.9343124 0.3524628
## degreeD     -0.0002940096 0.0008852016 -0.3321386 0.7405013
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0047074660 0.0048649767  0.9676235 0.3356639
## homophilyC  -0.0059662133 0.0095431230 -0.6251846 0.5333332
## degreeD     -0.0003932209 0.0007508467 -0.5237033 0.6016918
## Warning: Removed 2 rows containing non-finite values (`stat_smooth()`).
## Warning: Removed 2 rows containing non-finite values (`stat_cor()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).

## [1] "Regression on proportion of ever-isolated individuals, Control ; "
##                 Estimate  Std. Error   t value     Pr(>|t|)
## (Intercept)  0.015373230 0.004522443  3.399320 0.0009817388
## homophilyD   0.011524957 0.006913588  1.667001 0.0987400061
## degreeD     -0.003746316 0.001128924 -3.318483 0.0012754692
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.25 ; "
##                 Estimate  Std. Error    t value   Pr(>|t|)
## (Intercept)  0.008193275 0.003993379  2.0517150 0.04289229
## homophilyD   0.004605791 0.006680777  0.6894095 0.49221154
## degreeD     -0.002409296 0.001165034 -2.0680045 0.04130130
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.5 ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0030916793 0.0033054488  0.9353281 0.3519419
## homophilyD  -0.0009911549 0.0040349157 -0.2456445 0.8064764
## degreeD     -0.0005145388 0.0007900507 -0.6512732 0.5164101
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 0.75 ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0046780045 0.0036903307  1.2676383 0.2079617
## homophilyD   0.0031732969 0.0056504887  0.5615969 0.5756860
## degreeD     -0.0009610133 0.0007315371 -1.3136905 0.1920490
## [1] "Regression on proportion of ever-isolated individuals, degree %ile = 1 ; "
##                  Estimate   Std. Error    t value  Pr(>|t|)
## (Intercept)  0.0036515402 0.0045128565  0.8091417 0.4204556
## homophilyD   0.0031319315 0.0050037020  0.6259229 0.5328665
## degreeD     -0.0006535667 0.0007865756 -0.8309013 0.4081128
plot.trends <- 
  data.frame(
    trends.df %>% 
      group_by(round, V, GINI, fractionCoop) %>% 
      summarize_all(list(mean=~mean(., na.rm=TRUE),sd=~sd(., na.rm=TRUE)))
  )

plot.trends$V = factor(plot.trends$V)
plot.trends$GINI = factor(plot.trends$GINI)

for(i in unique(plot.trends$fractionCoop)){
  g.gini = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=gini_mean,group=interaction(GINI,V))) +
  geom_line(aes(color=GINI,linetype=V)) +
  geom_ribbon(aes(ymin = gini_mean - gini_sd, ymax = gini_mean + gini_sd, fill=GINI),alpha=0.3) +
  xlab("Round")+
  ylab("gini") +
  theme_bw() 

  g.gmd = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=gmd_mean,group=interaction(GINI,V))) +
    geom_line(aes(color=GINI,linetype=V)) +
    geom_ribbon(aes(ymin = gmd_mean - gmd_sd, ymax = gmd_mean + gmd_sd, fill=GINI),alpha=0.3) +
    xlab("Round")+
    ylab("gmd") +
    theme_bw() 
  
  g.avg_wealth = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=avg_wealth_mean,group=interaction(GINI,V))) +
    geom_line(aes(color=GINI,linetype=V)) +
    geom_ribbon(aes(ymin = avg_wealth_mean - avg_wealth_sd, ymax = avg_wealth_mean + avg_wealth_sd, fill=GINI),alpha=0.3) +
    xlab("Round")+
    ylab("avg_wealth") +
    theme_bw() 
  
  g.avg_coop = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=avg_coop_mean,group=interaction(GINI,V))) +
    geom_line(aes(color=GINI,linetype=V)) +
    geom_ribbon(aes(ymin = avg_coop_mean - avg_coop_sd, ymax = avg_coop_mean + avg_coop_sd, fill=GINI),alpha=0.3) +
    xlab("Round")+
    ylab("avg_coop") +
    theme_bw() 
  
  g.avg_degree = ggplot(data=plot.trends[plot.trends$fractionCoop==i,], aes(x=round,y=avg_degree_mean,group=interaction(GINI,V))) +
    geom_line(aes(color=GINI,linetype=V)) +
    geom_ribbon(aes(ymin = avg_degree_mean - avg_degree_sd, ymax = avg_degree_mean + avg_degree_sd, fill=GINI),alpha=0.3) +
    xlab("Round")+
    ylab("avg_degree") +
    theme_bw() 
   
  
  
  plot <- ggarrange(g.gini,g.gmd,g.avg_wealth,g.avg_coop,g.avg_degree,common.legend = TRUE,legend="bottom")
  print(annotate_figure(plot, top = text_grob(paste("Degree percentile of nodes assigned to defectors =",i), color = "black", face = "bold", size = 10)))
}
## Warning: Removed 6 rows containing missing values (`geom_line()`).
## Warning: Removed 6 rows containing missing values (`geom_line()`).

## Warning: Removed 6 rows containing missing values (`geom_line()`).

## Warning: Removed 6 rows containing missing values (`geom_line()`).

## Warning: Removed 6 rows containing missing values (`geom_line()`).

fig1 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = homophilyC, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("C-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig2 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = homophilyD, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("D-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig3 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = heterophily, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("Heterophily") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig4 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = homophilyC, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("C-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig5 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = homophilyD, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("D-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")


fig6 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = heterophily, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Heterophily") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

fig7 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = degreeD, color = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Mean degree of defectors") +  
  scale_color_viridis(option = "magma") +
  labs(color="Isolated \nindividuals (%)")

print(ggarrange(fig1,fig2,fig3,fig4,fig5,fig6,fig7,common.legend = TRUE,legend="right"))
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Removed 1 rows containing missing values (`geom_point()`).

fig1 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Isolated individuals (%)") 


fig2 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("Isolated individuals (%)") 


fig3 = ggplot(data = df.netIntLowDegree, 
                         aes(x = homophilyC, y = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("C-assortativity") + 
  scale_y_continuous("Isolated individuals (%)") 



fig4 = ggplot(data = df.netIntLowDegree, 
                         aes(x = homophilyD, y = percentIsolation*100)) + 
  geom_point() +
  scale_x_continuous("D-assortativity") + 
  scale_y_continuous("Isolated individuals (%)") 



print(ggarrange(fig1,fig2,fig3,fig4,common.legend = TRUE,legend="right"))
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).

reg.isolation = glm(percentIsolation*100 ~ degreeC + degreeD + homophilyC + homophilyD + heterophily, data=df.netIntLowDegree, family = gaussian(link = "identity"))
summary(reg.isolation)
## 
## Call:
## glm(formula = percentIsolation * 100 ~ degreeC + degreeD + homophilyC + 
##     homophilyD + heterophily, family = gaussian(link = "identity"), 
##     data = df.netIntLowDegree)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -0.4865  -0.1602  -0.0734   0.0011   5.7652  
## 
## Coefficients:
##              Estimate Std. Error t value Pr(>|t|)    
## (Intercept)  0.870079   0.227803   3.819 0.000151 ***
## degreeC      0.004878   0.064221   0.076 0.939490    
## degreeD     -0.040034   0.046272  -0.865 0.387365    
## homophilyC  -0.752265   0.663540  -1.134 0.257466    
## homophilyD   0.053946   0.279915   0.193 0.847254    
## heterophily -1.375094   0.985773  -1.395 0.163663    
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.4707909)
## 
##     Null deviance: 238.81  on 497  degrees of freedom
## Residual deviance: 231.63  on 492  degrees of freedom
##   (2 observations deleted due to missingness)
## AIC: 1046.1
## 
## Number of Fisher Scoring iterations: 2
#variance inflation factor
car::vif(reg.isolation)
##     degreeC     degreeD  homophilyC  homophilyD heterophily 
##    4.233107    3.189170    2.266295    1.479627    3.267568
reg.isolation = glm(percentIsolation*100 ~ degreeD + homophilyD, data=df.netIntLowDegree, family = gaussian(link = "identity"))
summary(reg.isolation)
## 
## Call:
## glm(formula = percentIsolation * 100 ~ degreeD + homophilyD, 
##     family = gaussian(link = "identity"), data = df.netIntLowDegree)
## 
## Deviance Residuals: 
##     Min       1Q   Median       3Q      Max  
## -0.3154  -0.1470  -0.0858  -0.0172   5.8542  
## 
## Coefficients:
##             Estimate Std. Error t value Pr(>|t|)   
## (Intercept)  0.41240    0.13418   3.074  0.00223 **
## degreeD     -0.07615    0.02667  -2.855  0.00448 **
## homophilyD   0.10356    0.23683   0.437  0.66209   
## ---
## Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1
## 
## (Dispersion parameter for gaussian family taken to be 0.4745905)
## 
##     Null deviance: 238.81  on 497  degrees of freedom
## Residual deviance: 234.92  on 495  degrees of freedom
##   (2 observations deleted due to missingness)
## AIC: 1047.1
## 
## Number of Fisher Scoring iterations: 2
#variance inflation factor
car::vif(reg.isolation)
##    degreeD homophilyD 
##   1.050707   1.050707
#double machine learning
library(DoubleML)
## Warning: package 'DoubleML' was built under R version 4.1.2
library(mlr3)
## Warning: package 'mlr3' was built under R version 4.1.2
library(mlr3learners)
## Warning: package 'mlr3learners' was built under R version 4.1.2
set.seed(3141)


##degreeC
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "degreeC",
                             x_cols = c("degreeD","homophilyC","homophilyD","heterophily"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): degreeC
## Covariates: degreeD, homophilyC, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 498
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): degreeC
## Covariates: degreeD, homophilyC, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 498
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##          Estimate. Std. Error t value Pr(>|t|)
## degreeC -0.0001741  0.0005757  -0.302    0.762
##degreeD
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "degreeD",
                             x_cols = c("degreeC","homophilyC","homophilyD","heterophily"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): degreeD
## Covariates: degreeC, homophilyC, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 498
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): degreeD
## Covariates: degreeC, homophilyC, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 498
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##          Estimate. Std. Error t value Pr(>|t|)
## degreeD -0.0008931  0.0005493  -1.626    0.104
##homophilyC
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "homophilyC",
                             x_cols = c("degreeC","degreeD","homophilyD","heterophily"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): homophilyC
## Covariates: degreeC, degreeD, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 498
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): homophilyC
## Covariates: degreeC, degreeD, homophilyD, heterophily
## Instrument(s): 
## No. Observations: 498
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##            Estimate. Std. Error t value Pr(>|t|)
## homophilyC -0.007106   0.005627  -1.263    0.207
##homophilyD
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "homophilyD",
                             x_cols = c("degreeC","degreeD","homophilyC","heterophily"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): homophilyD
## Covariates: degreeC, degreeD, homophilyC, heterophily
## Instrument(s): 
## No. Observations: 498
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): homophilyD
## Covariates: degreeC, degreeD, homophilyC, heterophily
## Instrument(s): 
## No. Observations: 498
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##            Estimate. Std. Error t value Pr(>|t|)
## homophilyD  0.001983   0.001863   1.064    0.287
##heterophily
dml_data = DoubleMLData$new(df.netIntLowDegree[complete.cases(df.netIntLowDegree[c("percentIsolation","degreeC","degreeD","homophilyC","homophilyD","heterophily")]),],
                             y_col = "percentIsolation",
                             d_cols = "heterophily",
                             x_cols = c("degreeC","degreeD","homophilyC","homophilyD"))
print(dml_data)
## ================= DoubleMLData Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): heterophily
## Covariates: degreeC, degreeD, homophilyC, homophilyD
## Instrument(s): 
## No. Observations: 498
# surpress messages from mlr3 package during fitting
lgr::get_logger("mlr3")$set_threshold("warn")

learner = lrn("regr.ranger", num.trees=500, mtry=floor(sqrt(4)), max.depth=5, min.node.size=2)
ml_l = learner$clone()
ml_m = learner$clone()

obj_dml_plr = DoubleMLPLR$new(dml_data, ml_l=ml_l, ml_m=ml_m)
obj_dml_plr$fit()
print(obj_dml_plr)
## ================= DoubleMLPLR Object ==================
## 
## 
## ------------------ Data summary      ------------------
## Outcome variable: percentIsolation
## Treatment variable(s): heterophily
## Covariates: degreeC, degreeD, homophilyC, homophilyD
## Instrument(s): 
## No. Observations: 498
## 
## ------------------ Score & algorithm ------------------
## Score function: partialling out
## DML algorithm: dml2
## 
## ------------------ Machine learner   ------------------
## ml_l: regr.ranger
## ml_m: regr.ranger
## 
## ------------------ Resampling        ------------------
## No. folds: 5
## No. repeated sample splits: 1
## Apply cross-fitting: TRUE
## 
## ------------------ Fit summary       ------------------
##  Estimates and significance testing of the effect of target variables
##             Estimate. Std. Error t value Pr(>|t|)
## heterophily  -0.01285    0.01399  -0.918    0.358
fig1 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = homophilyC, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("C-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig2 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = homophilyD, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("D-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig3 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeD, y = heterophily, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of defectors") + 
  scale_y_continuous("Heterophily") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig4 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = homophilyC, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("C-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig5 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = homophilyD, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("D-assortativity") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")


fig6 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = heterophily, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Heterophily") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

fig7 = ggplot(data = df.netIntLowDegree, 
                         aes(x = degreeC, y = degreeD, color = avgCoopFinal*100)) + 
  geom_point() +
  scale_x_continuous("Mean degree of cooperators") + 
  scale_y_continuous("Mean degree of defectors") +  
  scale_color_viridis(option = "magma") +
  labs(color="Cooperation in \nfinal round (%)")

print(ggarrange(fig1,fig2,fig3,fig4,fig5,fig6,fig7,common.legend = TRUE,legend="right"))
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Warning: Removed 2 rows containing missing values (`geom_point()`).
## Warning: Removed 1 rows containing missing values (`geom_point()`).
## Removed 1 rows containing missing values (`geom_point()`).

Several explanations

Evolution of cooperation

This seems to occur regardless of initial defector/cooperator position (the same number of C's become D's, and the same number of D's become C's)